package com.idanchuang.component.base;

import com.alibaba.fastjson.JSON;
import com.idanchuang.component.core.helper.ConfigRestTemplate;
import com.idanchuang.component.core.helper.EnvContext;
import com.idanchuang.component.logback.helper.LogContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.util.List;

/**
 * @author yjy
 * @date 2020/7/6 10:49
 **/
@Configuration
@ConditionalOnClass(RestTemplate.class)
public class ComponentBaseRestTemplateAutoConfiguration {

    private static final Logger log = LoggerFactory.getLogger(ComponentBaseRestTemplateAutoConfiguration.class);

    @Bean
    @ConditionalOnMissingBean(RestTemplate.class)
    public RestTemplate restTemplate() {
        return new RestTemplateBuilder().build();
    }

    @Bean
    @ConditionalOnMissingBean(ConfigRestTemplate.class)
    public ConfigRestTemplate configRestTemplate(List<RestTemplate> restTemplates) {
        for (RestTemplate restTemplate : restTemplates) {
            restTemplate.getInterceptors().add((request, body, execution) -> {
                try {
                    // 传递压测标
                    String currentEnv = EnvContext.getCurrentEnv();
                    if (currentEnv != null) {
                        String envHeaderName = EnvContext.getEnvHeaderName();
                        if (!request.getHeaders().containsKey(envHeaderName)) {
                            request.getHeaders().add(envHeaderName, currentEnv);
                        }
                    }
                    // 传递自定义链路id
                    String dcTraceId = EnvContext.getDcTraceId();
                    if (dcTraceId != null) {
                        String dcTraceIdHeaderName = EnvContext.getDcTraceIdHeaderName();
                        if (!request.getHeaders().containsKey(dcTraceIdHeaderName)) {
                            request.getHeaders().add(dcTraceIdHeaderName, dcTraceId);
                        }
                    }
                    // 传递环境变量
                    if (EnvContext.getAttributeCount() > 0) {
                        String attributes = JSON.toJSONString(EnvContext.getAttributes());
                        attributes = URLEncoder.encode(attributes, "UTF-8");
                        request.getHeaders().add(EnvContext.TRANSMIT_ATTRIBUTE_HEADER_NAME, attributes);
                    }
                } catch (Exception e) {
                    // 降级
                    LogContext.setKeyword("componentError");
                    log.error("RestTemplate Interceptor error", e);
                }
                return execution.execute(request, body);
            });
        }
        return new ConfigRestTemplate();
    }

}
